package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    private Socket socket;

    /**
     * 客户端构造器
     */
    public Client(){
        try {
            System.out.println("正在连接..");
            socket = new Socket("localhost",8088);
            System.out.println("与服务端建立连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动执行
     * 写出字符串
     */
    public void start(){
        Scanner scan = new Scanner(System.in);
        try{
            PrintWriter pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream())),true);

            while (true){
                Thread t = new Thread(new ServerHandler());
                t.setDaemon(true);
                t.start();


                System.out.println("请输入：");
                String s = scan.next();
                if ("exit".equals(s)) {
                    break;
                }else {
                    pw.println(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 主方法
     * @param args
     */
    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                BufferedReader br= new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()));
                String s;
                while ((s = br.readLine())!= null){
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
